package com.example.chatuidemo.slice;
import com.example.chatuidemo.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;
import java.util.ArrayList;
public class MessagePageListProvider extends BaseItemProvider {
    // 数据模型列表
    private ArrayList<MessageModel> datalist;
    // 上下文对象
    private Context context;
    // 自定义构造方法
    public MessagePageListProvider(Context context) {
        super();
        this.context = context;
        setupData();
    }
    // 创建模拟数据
    private void setupData() {
        datalist = new ArrayList<MessageModel>();
        for (int i = 0; i < 20; i++) {
            MessageModel model = new MessageModel(ResourceTable.Media_icon, String.format("和XX-%d的会话", i), "会话的详细内容", "3");
            datalist.add(model);
        }
    }
    // 设置列表项个数
    @Override
    public int getCount() {
        return datalist.size();
    }
    // 设置列表项对应的模型
    @Override
    public Object getItem(int i) {
        return datalist.get(i);
    }
    // 设置列表项对应id
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public Component getComponent(int i, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        // 从布局文件或复用池获取列表项组件
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_message_item, null, false);
        } else {
            cpt = convertComponent;
        }
        // 获取对应渲染组件
        Image image = (Image) cpt.findComponentById(ResourceTable.Id_image);
        Text title = (Text) cpt.findComponentById(ResourceTable.Id_title_text);
        Text detail = (Text) cpt.findComponentById(ResourceTable.Id_detail_text);
        Text unread = (Text) cpt.findComponentById(ResourceTable.Id_unread_text);
        // 根据模型数据设置UI
        MessageModel model = datalist.get(i);
        image.setPixelMap(model.icon);
        title.setText(model.title);
        detail.setText(model.detail);
        unread.setText(model.unreadCount);
        return cpt;
    }
}
